package com.bridgetek.carlauncher.bean;

import android.content.Context;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 调用高德定位API
 * 添加相应的权限
 *
 * 修改了常量值类
 * 修改了FirstFragment.java
 * 修改了LocationService.java
 * 修改了string文件
 * 修改了AndroidManifest.xml
 *
 */
public class Gps implements AMapLocationListener {
    /*******************************start*******************************/

    private LocationManager mLocationManager = null;
    private Context mContext;
    private AMapLocation mAMapLocation = null;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    public Gps(Context context) {
        mContext = context;

        /**
         * 获取卫星状态信息的监听
         */
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            sendGpsStatusBroadcast(-1);
        }
        mLocationManager.addGpsStatusListener(statusListener);

        /**
         * 高德定位
         */
        mLocationClient = new AMapLocationClient(mContext.getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        //Battery_Saving为低功耗模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setInterval(10000);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    public AMapLocation getAMapLocation() {
        return mAMapLocation;
    }

    public void closeLocation() {
        if (mLocationManager != null) {
            if (statusListener != null) {
                mLocationManager.removeGpsStatusListener(statusListener);
            }
            mLocationManager = null;
        }

        mLocationClient.stopLocation();
    }


    /**
     * 高德定位
     *
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {//定位成功
                mAMapLocation = aMapLocation;
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("WTF", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }


/**********************************************************end******************************************************/


    /**
     * 卫星状态监听器
     */

    private List<GpsSatellite> numSatelliteList = new ArrayList<GpsSatellite>(); // 卫星信号
    private final GpsStatus.Listener statusListener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) { // GPS状态变化时的回调，如卫星数
            if (mLocationManager != null) {
                GpsStatus status = mLocationManager.getGpsStatus(null); // 取当前状态
                int satelliteInfo = updateGpsStatus(event, status);
                int maxSnr = getMaxSnr();
                sendGpsStatusBroadcast(maxSnr);
            }

        }
    };

    /**
     * 返回卫星个数
     */
    private int updateGpsStatus(int event, GpsStatus status) {
        if (status != null && event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
            try {
                int maxSatellites = status.getMaxSatellites();
                Iterator<GpsSatellite> it = status.getSatellites().iterator();
                numSatelliteList.clear();
                int count = 0;
                while (it.hasNext() && count <= maxSatellites) {
                    GpsSatellite s = it.next();
                    numSatelliteList.add(s);
                    boolean b = s.usedInFix();
                    if (b) {
                        count++;
                    }

                }
                return count;
            } catch (Exception e) {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 返回信号强度
     *
     * @return
     */
    private int getMaxSnr() {
        if (numSatelliteList != null) {
            float[] snr = new float[numSatelliteList.size()];
            for (int i = 0; i < numSatelliteList.size(); i++) {
                snr[i] = numSatelliteList.get(i).getSnr();
            }
            if (snr.length == 0) {
                return 0;
            }
            float maxSnr = snr[0];
            for (int i = 0; i < snr.length; i++) {
                if (maxSnr < snr[i])
                    maxSnr = snr[i];
            }
            return (int) maxSnr;
        } else {
            return 0;
        }
    }

    /**
     * 发送卫星信号强度 广播
     */
    private void sendGpsStatusBroadcast(int single) {
        Intent intent = new Intent();
        intent.setAction("com.android.action.GPS_NUM_CHANGE");
        intent.putExtra("satellite_number", single);
        mContext.sendBroadcast(intent);
    }

}
